<template>
  <view class="pet-container">
    <view class="pet-info">
      <view class="pet-stage">当前阶段：<text class="stage-name">{{ stageName }}</text></view>
      <view class="pet-img-wrap" @click="petJump">
        <canvas canvas-id="petCanvas" class="pet-canvas"></canvas>
        <!-- <image v-else :src="petImg" mode="aspectFit" class="pet-img" /> -->
      </view>
      <view class="pet-progress">
        今日喝水+拉屎记录：<text class="progress-num">{{ todayCount }}</text> / {{ stage === 1 ? 3 : 6 }}
      </view>
      <view class="pet-desc">每天喝水+拉屎记录≥{{ stage === 1 ? 3 : 6 }}次，宠物即可成长！</view>
      <button class="show-all-btn" @click="showAllStages = true">查看所有成长形象</button>
    </view>
    <!-- 成长形象弹窗 -->
    <view v-if="showAllStages" class="pet-popup-mask" @click.self="showAllStages = false">
      <view class="pet-popup">
        <view class="popup-title">宠物各阶段形象预览</view>
        <view class="popup-list">
          <view v-for="(item, idx) in stagePreviewList" :key="idx" class="popup-item">
            <canvas :canvas-id="item.id" class="popup-canvas"></canvas>
            <view class="popup-desc">{{ item.name }}：{{ item.desc }}</view>
          </view>
        </view>
        <view style="width:100%;display:flex;justify-content:center;margin-top:auto;">
          <button class="close-btn" @click="showAllStages = false">关闭</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { 
  getLocalOpenid, 
  getDrinkRecords, 
  getPoopRecords, 
  getPetStage, 
  setPetStage, 
  getPetDirection, 
  setPetDirection,
  getPetLastGrowDate,
  setPetLastGrowDate,
  formatDate
} from '../../utils/storage.js'

export default {
  name: 'PetPage',
  data() {
    return {
      stage: 1, // 1~6
      stageName: '',
      petImg: '',
      todayCount: 0,
      vpetImg: '/static/pet/vpet-baby.png', // 像素风幼崽图片
      stageList: [
        { name: '幼崽期', type: 'init' },
        { name: '青年期', type: 'water' },
        { name: '青年期', type: 'poop' },
        { name: '成长期', img: '/static/pet/pet-stage3.png' },
        { name: '成熟期', img: '/static/pet/pet-stage4.png' },
        { name: '超体期', img: '/static/pet/pet-stage5.png' },
        { name: '完美体', img: '/static/pet/pet-stage6.png' }
      ],
      direction: 'init', // water or poop
      blink: false,
      jump: false,
      canvasTimer: null,
      blinkTimer: null,
      jumpOffset: 0,
      footShake: false,
      footShakeDir: 'left',
      showAllStages: false,
      stagePreviewList: [
        // 预留：直接替换点阵数组即可
        { id: 'previewEgg', name: '幼崽期', desc: '初始蛋形，呆萌可爱', matrix: null },
        { id: 'previewYouthWater', name: '青年期（水系）', desc: '水系成长，蓝色清新', matrix: null },
        { id: 'previewYouthPoop', name: '青年期（便便系）', desc: '便便系成长，粉色活泼', matrix: null },
        { id: 'previewGrow', name: '成长期', desc: '逐渐成长，形象更丰富', matrix: null },
        { id: 'previewMature', name: '成熟期', desc: '成熟稳重，金色点缀', matrix: null },
        { id: 'previewSuper', name: '超体期', desc: '超体进化，绿色能量', matrix: null },
        { id: 'previewPerfect', name: '完美体', desc: '最终形态，皇冠加身', matrix: null }
      ]
    }
  },
  mounted() {
    this.initPet()
    this.$nextTick(() => {
      this.drawPet()
      // 定时眨眼动画
      this.blinkTimer = setInterval(() => {
        this.blink = true
        this.drawPet()
        setTimeout(() => {
          this.blink = false
          this.drawPet()
        }, 180)
      }, 3000)
      // 初始化弹窗预览各阶段形象
      setTimeout(() => {
        this.drawStagePreview()
      }, 300)
    })
  },
  beforeUnmount() {
    if (this.blinkTimer) clearInterval(this.blinkTimer)
    if (this.canvasTimer) clearTimeout(this.canvasTimer)
  },
  methods: {
    initPet() {
      // 读取本地宠物阶段
      this.stage = getPetStage()
      this.updatePetSkin()
      this.checkGrow()
    },
    updatePetSkin() {
      // 前2阶段用SVG渲染
      if (this.stage === 1) {
        this.stageName = '幼崽期'
        this.direction = 'init'
      } else if (this.stage === 2) {
        // 判断进化方向
        this.stageName = '青年期'
        this.direction = getPetDirection()
      } else if (this.stage === 3) {
        this.stageName = '成长期'
        this.petImg = this.direction === 'water' ? '/static/pet/pet-stage3-water.png' : '/static/pet/pet-stage3-poop.png'
      } else {
        const info = this.stageList[this.stage - 1]
        this.stageName = info.name
        this.petImg = info.img
      }
    },
    async checkGrow() {
      // 使用本地缓存生成唯一标识符
      let openid = uni.getStorageSync('openid')
      if (!openid) {
        // 生成一个随机的唯一标识符作为openid
        openid = 'local_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
        uni.setStorageSync('openid', openid)
      }
      
      // 从本地缓存获取喝水和拉屎记录
      const todayStr = this.formatDate(new Date())
      
      // 获取喝水记录
      const drinkHistory = uni.getStorageSync('drinkHistory') || []
      const todayDrinkRecords = drinkHistory.filter(item => 
        item.date === todayStr && (item.openid === openid || !item.openid)
      )
      const todayDrink = todayDrinkRecords.length // 喝水记录次数，不是总量
      
      // 获取拉屎记录
      const poopHistory = uni.getStorageSync('poopHistory') || []
      const todayPoopRecords = poopHistory.filter(item => 
        item.date === todayStr && (item.openid === openid || !item.openid)
      )
      const todayPoop = todayPoopRecords.length // 拉屎记录次数
      this.todayCount = todayDrink + todayPoop
      // 第一次成长时判定方向
      let lastGrowDate = uni.getStorageSync('petLastGrowDate') || ''
      if (this.stage === 1 && this.todayCount >= 3 && lastGrowDate !== todayStr) {
        // 判断偏好
        let direction = todayDrink >= todayPoop ? 'water' : 'poop'
        this.direction = direction
        uni.setStorageSync('petDirection', direction)
        this.stage++
        uni.setStorageSync('petStage', this.stage)
        uni.setStorageSync('petLastGrowDate', todayStr)
        this.updatePetSkin()
        uni.showToast({ title: direction === 'water' ? '水系成长！' : '便便系成长！', icon: 'success' })
      } else if (this.stage > 1 && this.todayCount >= 6 && lastGrowDate !== todayStr && this.stage < 6) {
        this.stage++
        uni.setStorageSync('petStage', this.stage)
        uni.setStorageSync('petLastGrowDate', todayStr)
        this.updatePetSkin()
        uni.showToast({ title: '宠物成长啦！', icon: 'success' })
      }
    },
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    drawPet() {
      // 所有阶段都用canvas点阵绘制
      const ctx = uni.createCanvasContext('petCanvas', this)
      ctx.clearRect(0, 0, 320, 320)
      // 定义各阶段点阵（8x8或8x10）
      // 0空白，1黑色边缘，2橙色，3蓝色，4灰色脚，5绿色，6粉色，7金色
      const eggPet = [
        [0,0,0,1,1,0,0,0],
        [0,0,1,2,2,1,0,0],
        [0,1,2,3,2,2,1,0],
        [1,2,2,3,3,2,2,1],
        [1,2,3,2,2,3,2,1],
        [0,1,2,2,2,2,1,0],
        [0,0,4,0,4,0,0,0],
        [0,0,4,0,4,0,0,0]
      ]
      // 青年期（水系/便便系）
      const youthPetWater = [
        [0,0,1,3,3,1,0,0],
        [0,1,3,2,2,3,1,0],
        [1,3,2,2,2,2,3,1],
        [3,2,2,5,5,2,2,3],
        [3,2,5,5,5,5,2,3],
        [1,3,2,2,2,2,3,1],
        [0,1,3,3,3,3,1,0],
        [0,0,4,0,4,0,0,0]
      ]
      const youthPetPoop = [
        [0,0,1,6,6,1,0,0],
        [0,1,6,2,2,6,1,0],
        [1,6,2,2,2,2,6,1],
        [6,2,2,5,5,2,2,6],
        [6,2,5,5,5,5,2,6],
        [1,6,2,2,2,2,6,1],
        [0,1,6,6,6,6,1,0],
        [0,0,4,0,4,0,0,0]
      ]
      // 成长期
      const growPet = [
        [0,0,1,2,2,1,0,0],
        [0,1,2,5,5,2,1,0],
        [1,2,5,2,2,5,2,1],
        [2,5,2,3,3,2,5,2],
        [2,5,3,2,2,3,5,2],
        [1,2,5,2,2,5,2,1],
        [0,1,2,5,5,2,1,0],
        [0,0,4,0,4,0,0,0]
      ]
      // 成熟期
      const maturePet = [
        [0,0,1,7,7,1,0,0],
        [0,1,7,2,2,7,1,0],
        [1,7,2,2,2,2,7,1],
        [7,2,2,3,3,2,2,7],
        [7,2,3,2,2,3,2,7],
        [1,7,2,2,2,2,7,1],
        [0,1,7,7,7,7,1,0],
        [0,0,4,0,4,0,0,0]
      ]
      // 超体期
      const superPet = [
        [0,0,1,5,5,1,0,0],
        [0,1,5,3,3,5,1,0],
        [1,5,3,2,2,3,5,1],
        [5,3,2,6,6,2,3,5],
        [5,3,6,6,6,6,3,5],
        [1,5,3,2,2,3,5,1],
        [0,1,5,5,5,5,1,0],
        [0,0,4,0,4,0,0,0]
      ]
      // 完美体
      const perfectPet = [
        [0,0,1,7,7,1,0,0],
        [0,1,7,6,6,7,1,0],
        [1,7,6,2,2,6,7,1],
        [7,6,2,3,3,2,6,7],
        [7,6,3,2,2,3,6,7],
        [1,7,6,2,2,6,7,1],
        [0,1,7,7,7,7,1,0],
        [0,0,4,0,4,0,0,0]
      ]
      // 眨眼动画（顶部第1行全黑）
      const blinkRow = 0
      // 小脚位置（第6/7行第2/4格）
      let footPos = [ [6,2], [6,4], [7,2], [7,4] ]
      let footOffsetY = 0, footOffsetX = 0
      if (this.jump) footOffsetY = -1
      if (this.footShake) footOffsetX = this.footShakeDir === 'left' ? -1 : 1
      // 画布点阵区域20x20，点阵居中显示
      const gridSize = 16
      const offsetX = Math.floor((20 - 8) / 2)
      const offsetY = Math.floor((20 - 8) / 2) + this.jumpOffset / gridSize
      // 选择当前阶段点阵
      let petMatrix = eggPet
      if (this.stage === 2) petMatrix = this.direction === 'water' ? youthPetWater : youthPetPoop
      if (this.stage === 3) petMatrix = growPet
      if (this.stage === 4) petMatrix = maturePet
      if (this.stage === 5) petMatrix = superPet
      if (this.stage === 6) petMatrix = perfectPet
      // 绘制主体
      for (let y = 0; y < petMatrix.length; y++) {
        for (let x = 0; x < petMatrix[y].length; x++) {
          let val = petMatrix[y][x]
          if (val === 0) continue
          let color = '#fff'
          if (val === 1) color = '#222' // 黑色边缘
          if (val === 2) color = '#f7b04a' // 橙色
          if (val === 3) color = '#5b7fd6' // 蓝色
          if (val === 4) color = '#bbb' // 灰色脚
          if (val === 5) color = '#6fd6a0' // 绿色
          if (val === 6) color = '#ffb6c1' // 粉色
          if (val === 7) color = '#ffd700' // 金色
          ctx.setFillStyle(color)
          ctx.fillRect((offsetX + x) * gridSize, (offsetY + y) * gridSize, gridSize, gridSize)
        }
      }
      // 眨眼动画（顶部黑色条）
      if (this.blink) {
        ctx.setFillStyle('#222')
        for (let x = 3; x <= 4; x++) {
          ctx.fillRect((offsetX + x) * gridSize, (offsetY + blinkRow) * gridSize, gridSize, gridSize)
        }
      }
      // 小脚动画（左右抖动+跳跃）
      ctx.setFillStyle('#bbb')
      footPos.forEach(([y,x],i) => {
        let fx = x + (i<2 ? footOffsetX : -footOffsetX)
        ctx.fillRect((offsetX + fx) * gridSize, (offsetY + y + footOffsetY) * gridSize, gridSize, gridSize)
      })
      ctx.draw()
    },
    petJump() {
      if (this.jump) return
      this.jump = true
      this.jumpOffset = -18
      this.blink = true
      // 脚抖动动画
      let shakeCount = 0
      this.footShake = true
      this.footShakeDir = 'left'
      const shakeAnim = () => {
        this.footShakeDir = this.footShakeDir === 'left' ? 'right' : 'left'
        this.drawPet()
        shakeCount++
        if (shakeCount < 6) {
          setTimeout(shakeAnim, 60)
        } else {
          this.footShake = false
        }
      }
      shakeAnim()
      this.drawPet()
      this.canvasTimer = setTimeout(() => {
        this.jump = false
        this.jumpOffset = 0
        this.blink = false
        this.drawPet()
      }, 400)
    },
    drawStagePreview() {
      // 各阶段点阵（如需替换形象，直接替换下方数组即可）
      const eggPet = [
        [0,0,0,1,1,0,0,0],
        [0,0,1,2,2,1,0,0],
        [0,1,2,3,2,2,1,0],
        [1,2,2,3,3,2,2,1],
        [1,2,3,2,2,3,2,1],
        [0,1,2,2,2,2,1,0],
        [0,0,4,0,4,0,0,0],
        [0,0,4,0,4,0,0,0]
      ]
      // 预留：直接替换下方点阵即可
      const youthPetWater = [
        [0,0,1,3,3,1,0,0],
        [0,1,3,2,2,3,1,0],
        [1,3,2,2,2,2,3,1],
        [3,2,2,5,5,2,2,3],
        [3,2,5,5,5,5,2,3],
        [1,3,2,2,2,2,3,1],
        [0,1,3,3,3,3,1,0],
        [0,0,4,0,4,0,0,0]
      ]
      const youthPetPoop = [
        [0,0,1,6,6,1,0,0],
        [0,1,6,2,2,6,1,0],
        [1,6,2,2,2,2,6,1],
        [6,2,2,5,5,2,2,6],
        [6,2,5,5,5,5,2,6],
        [1,6,2,2,2,2,6,1],
        [0,1,6,6,6,6,1,0],
        [0,0,4,0,4,0,0,0]
      ]
      const growPet = [
        [0,0,1,2,2,1,0,0],
        [0,1,2,5,5,2,1,0],
        [1,2,5,2,2,5,2,1],
        [2,5,2,3,3,2,5,2],
        [2,5,3,2,2,3,5,2],
        [1,2,5,2,2,5,2,1],
        [0,1,2,5,5,2,1,0],
        [0,0,4,0,4,0,0,0]
      ]
      const maturePet = [
        [0,0,1,7,7,1,0,0],
        [0,1,7,2,2,7,1,0],
        [1,7,2,2,2,2,7,1],
        [7,2,2,3,3,2,2,7],
        [7,2,3,2,2,3,2,7],
        [1,7,2,2,2,2,7,1],
        [0,1,7,7,7,7,1,0],
        [0,0,4,0,4,0,0,0]
      ]
      const superPet = [
        [0,0,1,5,5,1,0,0],
        [0,1,5,3,3,5,1,0],
        [1,5,3,2,2,3,5,1],
        [5,3,2,6,6,2,3,5],
        [5,3,6,6,6,6,3,5],
        [1,5,3,2,2,3,5,1],
        [0,1,5,5,5,5,1,0],
        [0,0,4,0,4,0,0,0]
      ]
      const perfectPet = [
        [0,0,1,7,7,1,0,0],
        [0,1,7,6,6,7,1,0],
        [1,7,6,2,2,6,7,1],
        [7,6,2,3,3,2,6,7],
        [7,6,3,2,2,3,6,7],
        [1,7,6,2,2,6,7,1],
        [0,1,7,7,7,7,1,0],
        [0,0,4,0,4,0,0,0]
      ]
      // 预留：如需替换点阵，直接替换 previewArr 顺序即可
      const previewArr = [eggPet, youthPetWater, youthPetPoop, growPet, maturePet, superPet, perfectPet]
      // 颜色映射
      const colorMap = {
        0: '#fff', 1: '#222', 2: '#f7b04a', 3: '#5b7fd6', 4: '#bbb', 5: '#6fd6a0', 6: '#ffb6c1', 7: '#ffd700'
      }
      // 画布点阵区域8x8，canvas 96x96，点阵居中显示
      const gridSize = 10
      const offsetX = Math.floor((96/gridSize - 8) / 2)
      const offsetY = Math.floor((96/gridSize - 8) / 2)
      this.stagePreviewList.forEach((item, idx) => {
        const ctx = uni.createCanvasContext(item.id, this)
        ctx.clearRect(0, 0, 96, 96)
        const petMatrix = previewArr[idx]
        for (let y = 0; y < petMatrix.length; y++) {
          for (let x = 0; x < petMatrix[y].length; x++) {
            let val = petMatrix[y][x]
            if (val === 0) continue
            ctx.setFillStyle(colorMap[val])
            ctx.fillRect((offsetX + x) * gridSize, (offsetY + y) * gridSize, gridSize, gridSize)
          }
        }
        ctx.draw()
      })
    }
  },
  watch: {
    showAllStages(val) {
      if (val) {
        // 延迟确保弹窗和canvas节点已挂载
        setTimeout(() => {
          this.drawStagePreview()
        }, 120)
      }
    }
  }
}
</script>

<style scoped>
.pet-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #eaf4ff 0%, #fafdff 100%);
  padding: 48rpx 28rpx 72rpx 28rpx;
  box-sizing: border-box;
  font-family: 'Share Tech Mono', 'Orbitron', 'monospace';
  display: flex;
  flex-direction: column;
  align-items: center;
}
.pet-title {
  font-size: 48rpx;
  font-weight: 900;
  color: #4f8cff;
  margin-bottom: 32rpx;
  text-align: center;
  text-shadow: 0 0 12rpx #6fd6ff;
}
.pet-info {
  background: #fff;
  border-radius: 32rpx;
  box-shadow: 0 4rpx 24rpx 0 rgba(79,140,255,0.08);
  padding: 36rpx 24rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 90vw;
  max-width: 600rpx;
}
.pet-stage {
  font-size: 32rpx;
  color: #4f8cff;
  font-weight: 700;
  margin-bottom: 18rpx;
}
.stage-name {
  color: #6fd6ff;
  font-weight: 900;
  margin-left: 8rpx;
}
.pet-img-wrap {
  margin: 18rpx 0 28rpx 0;
  width: 320px;
  height: 320px;
  background: #eaf4ff;
  border-radius: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2rpx 12rpx 0 rgba(79,140,255,0.06);
}
.pet-img {
  width: 320px;
  height: 320px;
  image-rendering: pixelated;
}
.pet-progress {
  font-size: 28rpx;
  color: #222;
  margin-bottom: 12rpx;
}
.progress-num {
  color: #4f8cff;
  font-weight: bold;
  font-size: 32rpx;
}
.pet-desc {
  font-size: 24rpx;
  color: #888;
  margin-top: 8rpx;
  text-align: center;
}
.pet-canvas {
  width: 320px;
  height: 320px;
  background: transparent;
  display: block;
}
/* 成长形象弹窗样式 */
.pet-popup-mask {
  position: fixed;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.18);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}
.pet-popup {
  background: #fff;
  border-radius: 32rpx;
  box-shadow: 0 4rpx 24rpx 0 rgba(79,140,255,0.18);
  padding: 32rpx 24rpx 24rpx 24rpx;
  min-width: 340px;
  max-width: 90vw;
  max-height: 80vh;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.popup-title {
  font-size: 36rpx;
  font-weight: 900;
  color: #4f8cff;
  margin-bottom: 18rpx;
  text-align: center;
}
.popup-list {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 18rpx;
}
.popup-item {
  display: flex;
  align-items: center;
  gap: 18rpx;
  margin-bottom: 8rpx;
}
.popup-canvas {
  width: 96px;
  height: 96px;
  background: #eaf4ff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx 0 rgba(79,140,255,0.08);
}
.popup-desc {
  font-size: 24rpx;
  color: #4f8cff;
  font-weight: 700;
  flex: 1;
}
.close-btn {
  margin-top: 18rpx;
  background: #4f8cff;
  color: #fff;
  border-radius: 16rpx;
  font-size: 28rpx;
  padding: 12rpx 32rpx;
}
.show-all-btn {
  margin-top: 18rpx;
  background: #6fd6ff;
  color: #fff;
  border-radius: 16rpx;
  font-size: 28rpx;
  padding: 12rpx 32rpx;
}
</style>
